<?php defined('BASEPATH') || exit('No direct script access allowed');

/**
 * Content controller
 */
class Content extends Admin_Controller
{
    protected $permissionCreate = 'Area.Content.Create';
    protected $permissionDelete = 'Area.Content.Delete';
    protected $permissionEdit   = 'Area.Content.Edit';
    protected $permissionView   = 'Area.Content.View';

    /**
     * Constructor
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        $this->auth->restrict($this->permissionView);
        $this->load->model('area/area_model');
        $this->lang->load('area');

        $this->form_validation->set_error_delimiters("<span class='error'>", "</span>");

        Template::set_block('sub_nav', 'content/_sub_nav');

        Assets::add_module_js('area', 'area.js');
        Assets::add_css(['plugins/select2/select2.min.css', 'plugins/iCheck/all.css']);
        Assets::add_js([Template::theme_url('plugins/select2/select2.full.min.js'), Template::theme_url('plugins/iCheck/icheck.min.js')]);
    }

    /**
     * Display a list of Area data.
     *
     * @return void
     */
    public function index($filter = 'active', $offset = 0)
    {
        $where = ['areas.deleted' => 0];
        if ($filter == 'active') $where['areas.active'] = 1;
        $totalRows = $this->area_model->where($where)->count_all();
        // 搜索
        $q = $this->input->get('q');
        if (!empty($q)) {
            $totalRows = $this->area_model->select()->where($where)->like('area_name', $q)->count_all();
            $records   = $this->area_model->select()->where($where)->like('area_name', $q)->find_all();
        } else {
            $this->area_model->where($where);
        }
        // Deleting anything?
        if (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);
            $checked = $this->input->post('checked');
            if (is_array($checked) && count($checked)) {

                // If any of the deletions fail, set the result to false, so
                // failure message is set if any of the attempts fail, not just
                // the last attempt

                $result = true;
                foreach ($checked as $pid) {
                    $deleted = $this->area_model->delete($pid);
                    if ($deleted == false) {
                        $result = false;
                    }
                }
                if ($result) {
                    Template::set_message(count($checked) . ' ' . lang('area_delete_success'), 'success');
                } else {
                    Template::set_message(lang('area_delete_failure') . $this->area_model->error, 'error');
                }
            }
        }

        $pagerUriSegment = 6;
        $pagerBaseUrl    = site_url(SITE_AREA . '/content/area/index') . '/';

        $limit = $this->settings_lib->item('site.list_limit') ?: 15;

        $this->area_model->limit($limit, $offset);//->where($where);
        $records = !empty($records) ? $records : $this->area_model->find_all();
        if ($records) {
            foreach ($records as $key => $value) {
                $records[$key]->parent_name = $this->area_model->get_field($value->parent_id, 'area_name');
            }
        }
        Template::set('records', $records);

        // Used as the view's index_url and the base for the pager's base_url.
        Template::set('index_url', $pagerBaseUrl);

        // 分页
        $this->load->library('pagination');
        $this->pager['base_url']    = "{$pagerBaseUrl}{$filter}/";
        $this->pager['total_rows']  = $totalRows; //$this->area_model->where($where)->count_all();
        $this->pager['per_page']    = $limit;
        $this->pager['uri_segment'] = $pagerUriSegment;

        $this->pagination->initialize($this->pager);

        Template::set('filter_type', $filter);
        Template::set('toolbar_title', lang('area_manage'));
        Template::render();
    }

    /**
     * Create a Area object.
     *
     * @return void
     */
    public function create()
    {
        $this->auth->restrict($this->permissionCreate);

        if (isset($_POST['save'])) {
            if ($insert_id = $this->save_area()) {
                log_activity($this->auth->user_id(), lang('area_act_create_record') . ': ' . $insert_id . ' : ' . $this->input->ip_address(), 'area');
                Template::set_message(lang('area_create_success'), 'success');

                redirect(SITE_AREA . '/content/area');
            }

            // Not validation error
            if (!empty($this->area_model->error)) {
                Template::set_message(lang('area_create_failure') . $this->area_model->error, 'error');
            }
        }

        $provinces = $this->area_model->provinces();
        Template::set('provinces', $provinces);

        Template::set('toolbar_title', lang('area_action_create'));

        Template::render();
    }

    /**
     * Allows editing of Area data.
     *
     * @return void
     */
    public function edit()
    {
        $id = $this->uri->segment(5);
        if (empty($id)) {
            Template::set_message(lang('area_invalid_id'), 'error');

            redirect(SITE_AREA . '/content/area');
        }

        if (isset($_POST['save'])) {
            $this->auth->restrict($this->permissionEdit);

            if ($this->save_area('update', $id)) {
                log_activity($this->auth->user_id(), lang('area_act_edit_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'area');
                Template::set_message(lang('area_edit_success'), 'success');
                redirect(SITE_AREA . '/content/area');
            }

            // Not validation error
            if (!empty($this->area_model->error)) {
                Template::set_message(lang('area_edit_failure') . $this->area_model->error, 'error');
            }
        } elseif (isset($_POST['delete'])) {
            $this->auth->restrict($this->permissionDelete);

            if ($this->area_model->delete($id)) {
                log_activity($this->auth->user_id(), lang('area_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'area');
                Template::set_message(lang('area_delete_success'), 'success');

                redirect(SITE_AREA . '/content/area');
            }

            Template::set_message(lang('area_delete_failure') . $this->area_model->error, 'error');
        }

        $area = $this->area_model->find($id);
        Template::set('area', $area);

        // 这段代码暂时不会运行
        if ($area->area_type > 10) {
            $city_id = 0;

            $provinces = $this->area_model->provinces();
            Template::set('provinces', $provinces);

            $cities = $this->area_model->cities($area->parent_id);
            Template::set('cities', $cities);
        }

        Template::set('toolbar_title', lang('area_edit_heading'));
        Template::render();
    }

    //--------------------------------------------------------------------------
    // !PRIVATE METHODS
    //--------------------------------------------------------------------------

    /**
     * Save the data.
     *
     * @param string $type Either 'insert' or 'update'.
     * @param int    $id   The ID of the record to update, ignored on inserts.
     *
     * @return boolean|integer An ID for successful inserts, true for successful
     * updates, else false.
     */
    private function save_area($type = 'insert', $id = 0)
    {
        if ($type == 'update') {
            $_POST['area_id'] = $id;
        }

        // Validate the data
        $this->form_validation->set_rules($this->area_model->get_validation_rules());
        if ($this->form_validation->run() === false) {
            return false;
        }

        // Make sure we only pass in the fields we want

        $data = $this->area_model->prep_data($this->input->post());

        // Additional handling for default values should be added below,
        // or in the model's prep_data() method

        $return = false;
        if ($type == 'insert') {
            $id = $this->area_model->insert($data);

            if (is_numeric($id)) {
                $return = $id;
            }
        } elseif ($type == 'update') {
            $return = $this->area_model->update($id, $data);
        }

        return $return;
    }

    public function delete()
    {
        $id = $this->uri->segment(5);
        if (empty($id)) {
            Template::set_message(lang('vendor_invalid_id'), 'error');

            redirect(SITE_AREA . '/content/area');
        }

        $this->auth->restrict($this->permissionDelete);

        if ($this->area_model->delete($id)) {
            log_activity($this->auth->user_id(), lang('vendor_act_delete_record') . ': ' . $id . ' : ' . $this->input->ip_address(), 'area');
            Template::set_message(lang('area_delete_success'), 'success');

            redirect(SITE_AREA . '/content/area');
        }
    }

    public function ajax_area_data()
    {
        $parentID = $this->input->get('p_id');
        $data     = $this->area_model->provinces($parentID);
        $html     = '<option selected="selected" value="0">可选择</option>';
        if (!empty($data)) {
            foreach ($data as $obj) {
                $html .= '<option value="' . $obj->area_id . '">' . $obj->area_name . '</option>';
            }
        }
        echo $html;
    }

    public function ajax_upload()
    {
        $type = trim($this->input->get('type'));
        if (empty($type)) {
            $this->failure([], "缺少图片类型参数");
        }
        if ($_FILES) {
            $config['upload_path']   = './uploads/' . $type;
            $config['allowed_types'] = '*';
            $config['encrypt_name']  = true;
            $config['max_size']      = '500000';
            if (!file_exists($config['upload_path'])) {
                mkdir($config['upload_path'], 0777, true);
            }
            if ($_FILES['file']['name'] == '') {
                $this->failure([], "请选择图片");
            }
            $allowed_types = ['jpg', 'jpeg', 'png', 'bmp', 'gif'];
            $torrent       = explode(".", $_FILES['file']['name']);
            $fileend       = strtolower(end($torrent));
            if (!in_array($fileend, $allowed_types)) {
                $this->failure([], "图片类型不正确");
            }
            $this->load->library('upload', $config);
            if (!$this->upload->do_upload('file')) {
                $this->failure([], "上传失败");
            } else {
                //upload sucess
                $data = $this->upload->data();
                if (!empty($data['full_path'])) {
                    $this->success([
                        'path'      => 'uploads/' . $type . "/" . $data['file_name'],
                        'url'       => site_url('uploads/' . $type . "/" . $data['file_name']),
                        'orig_name' => $data['orig_name'],
                    ]);
                } else {
                    $this->failure([], "图片设置错误");
                }
            }
        } else {
            $this->failure([], "请选择图片");
        }
    }
}